/***************************firefoxupdater.cpp******************************/
/*****************************************************************************/
/*******************Browsers Daily Build Updater************************/
/************Copyright (C) 2010-2011  Gianluigi Biancucci*************/
/*****************************************************************************/
/*****This is free software, and you are welcome to redistribute it****/
/*****and / or modify underthe terms of GPLV2 License.**************/
/*****This program comes with ABSOLUTELY NO WARRANTY*****/
/*****************************************************************************/

#include "FirefoxUpdater.h"
#include "singletondownloader.h"
#include "iostream"
#include "QFile"
#include <QMessageBox>
#include <QIcon>
#include <QLabel>
#include <QDir>
#include <QProcess>
#include <QStringList>
#include "firefoxupdater.h"
#include "paths.h"
#include <QVariant>
#include "OSDaB-Zip\unzip.h"
FirefoxUpdater::FirefoxUpdater(QString arch, QString installPath)

{


    downloader = SingletonDownloader::getInstance();
    QDir dir;
    dir = QDir();
    if(!dir.exists(FFOXSETPATH+"/"))dir.mkdir(FFOXSETPATH+"/");
    _64="win64-x86_64";
    _32="win32";

    currPath.setPath(installPath);
    qDebug(currPath.path().toStdString().c_str());
    this->setArch(arch);
    brenchNum = "";
    BName = "Firefox";
    lastError ="No Error";

}



void FirefoxUpdater::setArch(QString arch){

    if(arch == "32"){
        currOsType=_32;
    }
    else {
        currOsType=_64;
    }
}


bool FirefoxUpdater::downloadLatest(QString * exePath){

    //Path 64 bit http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-4.0b8pre.en-US.win64-x86_64.installer.exe
    //Path 32 bit http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-4.0b8pre.en-US.win32.installer.exe
    QByteArray  res;
    if(!downloader->syncGet("http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/",&res)){
        lastError ="Undefined error (1b) when downloading nighty build page of Firefox.\nCheck your connection settings and try again.";
        return false;
    }
    QString page(res);
    brenchNum=this->getContentBetween(page,"firefox-","."+currOsType+".txt");

    QByteArray verBA;
    downloader->syncGet("http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-"+brenchNum+"."+currOsType+".txt",&verBA);
    QString verTStamp(verBA);
    if(verTStamp.isEmpty())verTStamp="latest";
    verTStamp.remove(14,verTStamp.length());

    QByteArray firefox;
    if( downloader->syncGet("http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-"+brenchNum+"."+currOsType+".zip",&firefox)){

        QFile* ffile = new QFile(FFOXSETPATH+"/firefox_"+currOsType+"_"+verTStamp+".zip");
        ffile->open(QIODevice::WriteOnly);
        ffile->write(firefox);
        ffile->close();
        delete ffile;
        *exePath =  FFOXSETPATH+"/firefox_"+currOsType+"_"+verTStamp+".zip";
        return true;
    } else {
        QString p = "http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-"+brenchNum+"."+currOsType+".zip";
        qDebug(p.toStdString().c_str());
        lastError ="Undefined error (3) when downloading Firefox installer.\nCheck your connection settings and try again.";
        return false;
    }
}




bool  FirefoxUpdater::getLatestVersion(QString * lastVer){

    QByteArray  res;
    if(!downloader->syncGet("http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/",&res)){
        lastError ="Undefined error (1) when downloading nighty build page of Firefox.\nCheck your connection settings and try again.";
        return false;
    }
    QString page(res);
    brenchNum=this->getContentBetween(page,"firefox-","."+currOsType+".txt");
    qDebug(brenchNum.toStdString().c_str());
    QByteArray verBA;
    if(!downloader->syncGet("http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-"+brenchNum+"."+currOsType+".txt",&verBA)){

        lastError ="Undefined error (2) when checking the last version od Firefox.\nCheck your connection settings and try again.";
        return false;

    }

    QString verTStamp(verBA);
    verTStamp.remove(14,verTStamp.length());
    *lastVer=verTStamp;
    return true;
}

bool  FirefoxUpdater::getInstalledVersion(QString * installedVer){

    if(currPath.exists("application.ini")){

        QFile iniFile(currPath.path()+"/application.ini");
        iniFile.open(QIODevice::ReadOnly);
        QByteArray  fileBA=iniFile.readAll();
        iniFile.close();
        QString fileStr(fileBA);
        int start=fileStr.indexOf("BuildID=");
        if (start!=-1){
            fileStr.remove(0,start+8);
            fileStr.remove(14,fileStr.length());
            *installedVer=fileStr;
            return true;

        }else {
            lastError="Cannot retrieve Firefox version.Sorry.";
            return false;

        }


    }else{
        lastError="Cannot detect Firefox version. Maybe corrupted installation or wrong path. Check settings.";
        return false;
    }
}

bool FirefoxUpdater::install(QString zipPath){

    UnZip uz;

    //Open Zip file
    UnZip::ErrorCode ec = uz.openArchive(zipPath);
    if (ec != UnZip::Ok) {
        lastError="Cannot open Firefox archive.\nTry manual installation.";
        return false;
    }

    //Extract zip file in temporary path
    ec =      uz.extractAll(FFOXSETPATH+"/temp/");
    if (ec != UnZip::Ok) {
        lastError="Cannot extract Firefox.\nTry manual installation.";
        return false;
    }

    //close zip file
    uz.closeArchive();

    //delete current firefox install folder for a new fresh install (user data obviously ramains)
   /* QString delCmd = "rmdir \""+currPath.path()+"/\"";
    delCmd.replace("/","\\");
    delCmd+=" /S /Q";
    qDebug(delCmd.toStdString().c_str());
    system(delCmd.toStdString().c_str());*/

    //copy the new firefox version in the install path
    QString copyCmd = "xcopy "+FFOXSETPATH+"/temp/firefox/* \""+currPath.path()+"\"";
    copyCmd.replace("/","\\");
    copyCmd+=" /E /H /I /K /Y";
    qDebug(copyCmd.toStdString().c_str());
    system(copyCmd.toStdString().c_str());

    //delete the temporary zip file path
    QString delCmd = "rmdir "+FFOXSETPATH+"/temp";
    delCmd.replace("/","\\");
    delCmd+=" /S /Q";
    qDebug(delCmd.toStdString().c_str());
    system(delCmd.toStdString().c_str());

    QMessageBox msg;
    msg.setWindowTitle("Update Ok");
    msg.setIcon(QMessageBox::Information);
    msg.setText("Firefox succesfully updated.\n("+currPath.path()+")");
    msg.exec();


    return true;
}

QString FirefoxUpdater::getContentBetween(QString source, QString startStr, QString endStr){

    int end = source.lastIndexOf(endStr);
    if(end != -1){
        source = source.remove(end,source.length()-(end));
        int start =0;
        QString sourcecopy = source;
        while (start != -1){
            start = sourcecopy.indexOf(startStr);
            if (start != -1) {
                sourcecopy=sourcecopy.remove(0,start+startStr.length());
                source = sourcecopy;
            }
        }
    }
    return source;
}

bool FirefoxUpdater::checkInstallPath(){
    if(currPath.exists("firefox.exe"))return true;
    else return false;
}


QString FirefoxUpdater::getBrowserName(){

    return BName;

}

QString FirefoxUpdater::getLastError(){

    return lastError;

}
